<template>
  <el-dialog v-model="visible" :title="title" width="70%">
    <el-table
      ref="tableRef"
      v-loading="loading"
      :data="dataList"
      @selection-change="handleSelectionChange"
      style="width: 100%"
      :row-key="getRowKey"
      reserve-selection
    >
      <el-table-column type="selection" width="55" />
      <el-table-column
        v-for="(label, field) in dictFields"
        :key="field"
        :prop="field"
        :label="label"
      >
        <template #default="{ row }">
          {{ row[field] || '-' }}
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="handlePageChange"
    />

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="handleConfirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, nextTick } from 'vue'
import { listTableData } from "@/api/online";

interface Mapping {
  [key: string]: string
}

const props = defineProps({
  visible: Boolean,
  title: String,
  selectedValues: {
    type: Array as PropType<any[]>, // 明确数组类型
    default: () => []
  },
  dictType: {
    type: String,
    required: true
  },
  dictFields: {
    type: Object,
    default: () => ({})
  },
  mapping: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['update:visible', 'select'])

const visible = ref(false)
const loading = ref(false)
const dataList = ref<any[]>([])
const total = ref(0)
const tableRef = ref();
const getRowKey = (row: any) => {
  return row[Object.keys(props.dictFields)[0]];
};

watch(() => props.selectedValues, (newVal) => {
  nextTick(() => {
    dataList.value.forEach(row => {
      const key = getRowKey(row);
      const isSelected = newVal.includes(key);
      tableRef.value?.toggleRowSelection(row, isSelected);
    });
  });
}, { immediate: true, deep: true });

const queryParams = ref({
  pageNum: 1,
  pageSize: 10
})
const selectedRows = ref<any[]>([])

//同步内部状态到父组件
watch(visible, (newVal) => {
  emit('update:visible', newVal)
})

watch(() => props.visible, val => {
  visible.value = val
  if (val) {
    resetQuery()
    getList()
  }
})

const getList = async () => {
  try {
    loading.value = true
    const res = await listTableData(
      props.dictType,
      queryParams.value
    )
    dataList.value = res.rows
    total.value = res.total
  } finally {
    loading.value = false
  }
}

const handlePageChange = (pagination: any) => {
  queryParams.value.pageNum = pagination.pageNum
  queryParams.value.pageSize = pagination.pageSize
  getList()
}

const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

const handleConfirm = () => {
  if (selectedRows.value.length === 0) return
  console.log("handleConfirm props.mapping",props.mapping)
  const mappedData = selectedRows.value.map(row => {
    console.log("handleConfirm row",row)
    const result: any = {}
    Object.entries(props.mapping).forEach(([srcField, targetField]) => {
      result[targetField] = row[srcField]
    })
    console.log("handleConfirm result",result)
    return result
  })

  emit('select', mappedData.length === 1 ? mappedData[0] : mappedData)
  visible.value = false
}

const resetQuery = () => {
  queryParams.value.pageNum = 1
  queryParams.value.pageSize = 10
}
</script>
